package com.millstein.eduservice.controller;


import com.millstein.commonutils.Result;
import com.millstein.eduservice.client.VodClient;
import com.millstein.eduservice.entity.EduVideo;
import com.millstein.eduservice.service.EduVideoService;
import com.millstein.servicebase.handler.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-07-15
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient vodClient;

    /**
     * 新增小节
     * @param eduVideo
     * @return
     */
    @PostMapping
    public Result addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return Result.ok();
    }

    /**
     * 根据id删除小节
     * @param videoId
     * @return
     */
    @DeleteMapping("/{videoId}")
    public Result deleteVideo(@PathVariable("videoId") String videoId) {
        // 1.根据小节id得到视频id
        EduVideo dbVideo = eduVideoService.getById(videoId);
        // 2.判断小节中是否保存了视频id
        if (!StringUtils.isEmpty(dbVideo.getVideoSourceId())) {
            // 有值再删
            Result result = vodClient.removeAliyunVideo(dbVideo.getVideoSourceId());
            if (!result.getSuccess()) {
                throw new GuliException(20001, "触发了熔断器，删除失败");
            }
        }
        // 3.删掉数据库中的小节信息
        eduVideoService.removeById(videoId);
        return Result.ok();
    }

    /**
     * 修改小节
     * @param eduVideo
     * @return
     */
    @PutMapping
    public Result updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return Result.ok();
    }

    /**
     * 根据id查询小节
     * @param videoId
     * @return
     */
    @GetMapping("/getVideoInfo/{videoId}")
    public Result getVideoInfo(@PathVariable("videoId") String videoId) {
        EduVideo video = eduVideoService.getById(videoId);
        return Result.ok().data("video", video);
    }

}

